<template>
  <div>
    <el-form ref="editForm" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="名称" prop="title">
            <el-input v-model="formItem.title" placeholder="请输入规则名称" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="知识库类型" prop="knowledgeTypeCode">
            <treeselect
              v-model="formItem.knowledgeTypeCode"
              :multiple="false"
              :options="availableOganizations"
              placeholder="请选择知识库类型"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="关键字">
            <el-input v-model="test" placeholder="输入关键字，按回车添加" @change="add" />
            <div v-if="formItem.keywords.length > 0" class="fix-input-prefix2">
              <el-tag v-for="tag in formItem.keywords" :key="tag.name" size="mini" closable type="success" @close="removeUser(tag)">{{ tag.name }}</el-tag>
              <i class="el-icon-close" title="清除所有值" @click="clearAllUser" />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件">
            <el-upload
              class="upload-demo"
              :headers="headers"
              :action="importUrl"
              :file-list="formItem.attachment"
              :before-upload="handleBeforeUpLoad"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-remove="handleRemove"
              :show-file-list="true"
            >
              <el-button size="small" type="primary" icon="el-icon-upload2">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="">
            <!-- <Tinymce ref="tinymce" v-model="formItem.content" :height="300" menubar="false" /> -->
            <el-input v-model="formItem.content" placeholder="请输入内容" :rows="10" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
// import Tinymce from '@neu/biz-core/components/Tinymce'
// import MarkdownEditor from '@neu/biz-core/components/MarkdownEditor'
import treeselect from '@neu/biz-core/components/TreeSelect'
import { create, update, detail, importUrl, deleteAttachmentByFsId } from '@neu/dcom-ui/api/knowledge'
import { tree } from '@neu/dcom-ui/api/knowledgeType'
import { clone } from '@neu/biz-core/utils/utils'
import { getToken } from '@neu/biz-core/utils/auth'

// 定义一个表单原始项
const formItem = {
  /** 标题 */
  title: '',
  /** 类型 */
  knowledgeTypeCode: null,
  /** 内容 */
  content: '',
  // 附件列表
  attachment: [],
  // 关键字
  keywords: [],
  // 关键字名称列表
  // keywordsName: [],
  // 阅读量
  // readingVolume: '',
  // 创建人编码
  usercode: '',
  // 创建人名称
  username: '',
  // 评论
  comment: []
}
export default {
  name: 'KonwledgeViewEdit',
  components: {
    treeselect,
    // quillEditor
    // MarkdownEditor
    // Tinymce
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      content: null,
      editorOption: {},
      importUrl: importUrl,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      availableOganizations: [],
      inspectionTypes: [],
      // 编辑的表单内容
      formItem: clone(formItem),
      // 表单验证规则
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'change' }],
        knowledgeTypeCode: [{ required: true, message: '类型不能为空', trigger: 'change' }]
      },
      test: ''
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    // findByDictionaryType('projectType').then(response => {
    //   this.projectTypes = response.data
    // })
    tree().then(response => {
      this.availableOganizations = response.data
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = clone(formItem)
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.editForm.resetFields()
      this.formItem = clone(this.formItem)
    },

    /** 组织机构赋值 */
    selcetOrg(value) {
      // this.formItem.orgName = value.title
    },
    inputOrg(value) {
      // const obj = this.formItem.inspectionType
      // this.formItem.inspectionType = ''
      // if (value === undefined) {
      //   this.formItem.orgName = ''
      //   this.inspectionTypes = []
      // } else {
      //   const params = {
      //     's_orgCode': this.formItem.orgCode
      //   }
      //   list(params).then(response => {
      //     this.inspectionTypes = response.data
      //     this.formItem.inspectionType = Number(obj) === 0 ? '' : Number(obj)
      //   })
      // }
    },
    handleBeforeUpLoad(file) {
      // if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
      //   this.$message({
      //     showClose: true,
      //     message: '文件 ' + file.name + ' 格式不正确，请上传.xls,.xlsx文件。',
      //     type: 'error'
      //   })
      // }
    },
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '文件上传成功',
          type: 'success'
        })
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        console.log(obj)
        const fsIdArr = this.formItem.attachment.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachment.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    handleError(err, file, fileList) {
      console.log(err)
    },
    handleRemove(file, fileList) {
      this.formItem.attachment = this.formItem.attachment.filter(t => {
        return t.fsId !== file.fsId
      })
      if (this.id !== -1) {
        return
      }
      deleteAttachmentByFsId(file.fsId, this.id).then(res => {
        // if (res.status === 'failure') {
        //   this.$message({
        //     showClose: true,
        //     message: res.data,
        //     type: 'error'
        //   })
        // } else {
        //   this.$message({
        //     showClose: true,
        //     message: '删除成功',
        //     type: 'success'
        //   })
        // }
      })
    },
    /** 删除某一项 */
    removeUser(tag) {
      this.formItem.keywords = this.formItem.keywords.filter(t => {
        return t.name !== tag.name
      })
    },
    /** 删除所有项 */
    clearAllUser() {
      this.formItem.keywords = []
    },
    add(value) {
      const keywordsName = this.formItem.keywords.map(t => t.name)
      if (!keywordsName.includes(value)) {
        const obj = {
          name: value
        }
        this.formItem.keywords.push(obj)
        this.test = ''
      }
      console.log(value)
    }
  }
}
</script>

